package com.heima.comment.service.impl;



import com.heima.comment.feign.MediaFeign;
import com.heima.comment.service.IAuditService;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;

import com.heima.common.util.SensitiveWordUtil;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Map;


/**
 * @Author WSJ
 * @Date 2022-03-14-15:34
 * @Version 1.0 （版本号）
 */
@Service
public class AuditServiceImpl implements IAuditService {
    @Autowired
    private GreenTextScan textScan;

    @Autowired
    private MediaFeign mediaFeign;

    @Override
    public boolean audit(String comment) {
        //审核自定义敏感词
        Boolean audit=auditFromSql(comment);
        if (!audit) {
            return false;
        }
        //阿里云审核文本
        Boolean aBoolean = auditTextByAliyun(comment);
        if (!aBoolean) {
            return false;
        }
        //全部通过
        return true;
    }

    /**
     * 阿里云审核文本
     * @param text
     * @return
     */
    public Boolean auditTextByAliyun(String text) {
        try {
            //阿里云审核文本
            Map map = textScan.greenTextScan( text);
            String suggestion = (String) map.get("suggestion");
            //根据审核结果设置状态
            switch (suggestion){
                case "pass":{
                    //审核通过
                    return true;
                }
                case "block":{
                    break;
                }
                case "review":{
                    break;
                }
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 审核自定义敏感词
     * @param text
     * @return
     */
    private Boolean auditFromSql(String text) {
        //获取敏感词集合
        //构建查询条件
        ResponseResult<List<String>> result = mediaFeign.find();
        List<String> list=null;
        if (result.getCode()== AppHttpCodeEnum.SUCCESS.getCode()) {
            list = result.getData();
        }
        //生成关键字字典库
        if (SensitiveWordUtil.dictionaryMap.size()==0) {
            SensitiveWordUtil.initMap(list);
        }
        //审核内容
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if (map.size()!=0) {
            //审核不通过
            return false;
        }
        //通过了，返回true
        return true;
    }
}
